package cn.com.epicc.wap.epe.common.exception.handler;


import cn.com.epicc.wap.epe.common.exception.EpeException;
import cn.com.epicc.wap.epe.common.result.Result;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


/**
 * Description: 通用异常处理<br>
 * Author: lishangmin<br>
 * Created: 2018-05-31 17:20<br>
 */
@ControllerAdvice
@ResponseBody
public class EpeExceptionHandler {

	@ExceptionHandler(value=Exception.class)
	public Result<String> exceptionHandler(Exception e){
	    //自定义异常
		if(e instanceof EpeException) {
			EpeException ex = (EpeException) e;
			return Result.error(ex.getMessage());
		}
		//数据绑定异常
		else if(e instanceof BindException) {
			BindException ex = (BindException)e;
			List<ObjectError> errors = ex.getAllErrors();
			ObjectError error = errors.iterator().next();
			String msg = error.getDefaultMessage();
			return Result.error(msg);
		}
		//其他异常
		else{
			return Result.error();
		}
	}
}
